package com.ruoyi.iot.utils;

import com.ruoyi.integration.response.DustResponse;
import com.ruoyi.integration.response.WeatherResponse;
import com.ruoyi.iot.dto.Dust;
import com.ruoyi.iot.dto.Weather;


import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


public class IoTConverter {

    // 定义 varName 到字段名的映射表（可根据 channelId 或 varName 匹配）
    private static final Map<String, String> FIELD_MAPPING = createFieldMapping();

    private static Map<String, String> createFieldMapping() {
        Map<String, String> map = new HashMap<>();
        map.put("空气温度_°C", "airTemperature");
        map.put("空气湿度_%", "airHumidity");
        map.put("气压_hPa", "pressure");
        map.put("风速_m/s", "windSpeed");
        map.put("风向_度", "windDirection");
        map.put("紫外指数", "uvIndex");
        map.put("太阳辐射_W/m2", "solarRadiation");
        map.put("日蒸发_mm", "dailyEvaporation");
        map.put("雨量_mm", "rainfall");
        map.put("土壤VWC1_m3/m3", "soilVwc1");
        map.put("土壤温度1_°C", "soilTemperature1");
        map.put("土壤EC1_ds/m", "soilEC1");
        map.put("土壤VWC2_m3/m3", "soilVwc2");
        map.put("土壤温度2_°C", "soilTemperature2");
        map.put("土壤EC2_ds/m", "soilEC2");
        return Collections.unmodifiableMap(map);
    }

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static List<Weather> weatherDataConvert(WeatherResponse response) {
        if (response == null || response.getResult() == null || response.getResult().getDataValues() == null) {
            return new ArrayList<>();
        }

        List<WeatherResponse.DataValue> dataValues = response.getResult().getDataValues();
        String sensorId = response.getResult().getDeviceId();

        // 按时间分组 dataValues
        Map<String, List<WeatherResponse.DataValue>> groupedByTime = dataValues.stream()
                .collect(Collectors.groupingBy(WeatherResponse.DataValue::getVarDate));

        return groupedByTime.entrySet().stream()
                .map(entry -> {
                    String varDateStr = entry.getKey();
                    LocalDateTime dataTime = LocalDateTime.parse(varDateStr, DATE_TIME_FORMATTER);
                    List<WeatherResponse.DataValue> valuesAtTime = entry.getValue();

                    // 构建单条 Weather 记录
                    Weather weather = new Weather();
                    weather.setSensorId(sensorId);
                    weather.setDataTime(dataTime);
                    weather.setInterfaceId(1); // 默认接口编号，可配置

                    for (WeatherResponse.DataValue dv : valuesAtTime) {
                        String fieldName = FIELD_MAPPING.get(dv.getVarName());
                        if (fieldName == null) continue;

                        Float value = parseFloat(dv.getValue());

                        switch (fieldName) {
                            case "airTemperature": weather.setAirTemperature(value); break;
                            case "airHumidity": weather.setAirHumidity(value); break;
                            case "pressure": weather.setPressure(value); break;
                            case "windSpeed": weather.setWindSpeed(value); break;
                            case "windDirection": weather.setWindDirection(value); break;
                            case "uvIndex": weather.setUvIndex(value); break;
                            case "solarRadiation": weather.setSolarRadiation(value); break;
                            case "dailyEvaporation": weather.setDailyEvaporation(value); break;
                            case "rainfall": weather.setRainfall(value); break;
                            case "soilVwc1": weather.setSoilVwc1(value); break;
                            case "soilTemperature1": weather.setSoilTemperature1(value); break;
                            case "soilEC1":
                                // 单位转换: dS/m -> μS/cm （1 dS/m = 1000 μS/cm）
                                weather.setSoilEC1(value);
                                break;
                            case "soilVwc2": weather.setSoilVwc2(value); break;
                            case "soilTemperature2": weather.setSoilTemperature2(value); break;
                            case "soilEC2":
                                weather.setSoilEC2(value);
                                break;
                        }
                    }
                    return weather;
                })
                .collect(Collectors.toList());
    }

    private static Float parseFloat(String str) {
        if (str == null || str.trim().isEmpty()) return null;
        try {
            return Float.parseFloat(str.trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }


    public static List<Dust> dustDataConvert(DustResponse response) {
        if (response == null || response.getData() == null) {
            return new ArrayList<>();
        }

        return response.getData().stream()
                .map(deviceData -> {
                    // 创建 Dust 对象
                    Dust dust = new Dust();
                    dust.setSensorId(String.valueOf(deviceData.getDeviceAddr()));
                    dust.setEquipmentStatus(mapDeviceStatus(deviceData.getDeviceStatus()));

                    // 时间戳转换（毫秒 → LocalDateTime） 使用 Asia/Shanghai
                    dust.setDataTime(LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(String.valueOf(deviceData.getTimeStamp()))), ZoneId.of("Asia/Shanghai")));


                    // 初始化所有数值字段为 null
                    initializeDustFields(dust);

                    // 遍历所有 dataItem 和 registerItem，填充数据
                    if (deviceData.getDataItem() != null) {
                        for (DustResponse.DataItem dataItem : deviceData.getDataItem()) {
                            if (dataItem.getRegisterItem() != null) {
                                for (DustResponse.RegisterItem reg : dataItem.getRegisterItem()) {
                                    setDustFieldValue(dust, reg.getRegisterName(), reg.getValue(), reg.getData());
                                }
                            }
                        }
                    }

                    return dust;
                })
                .collect(Collectors.toList());
    }

    /**
     * 初始化 Dust 对象所有数值字段为 null
     */
    private static void initializeDustFields(Dust dust) {
        dust.setWindPower(null);
        dust.setWindSpeed(null);
        dust.setWindDirection(null);
        dust.setTemperature(null);
        dust.setHumidity(null);
        dust.setAtmos(null);
        dust.setIllumination(null);
        dust.setPm10(null);
        dust.setPm25(null);
        dust.setTsp(null);
    }

    /**
     * 根据 registerName 设置 Dust 对象对应字段的值
     */
    private static void setDustFieldValue(Dust dust, String registerName, double value, String dataStr) {
        switch (registerName) {
            case "风力":
                dust.setWindPower(value);
                break;
            case "风速":
                dust.setWindSpeed(value);
                break;
            case "风向":
                dust.setWindDirection(dataStr); // 使用字符串值（如“东北风”）
                break;
            case "温度":
                dust.setTemperature(value);
                break;
            case "湿度":
                dust.setHumidity(value);
                break;
            case "大气压":
                dust.setAtmos(value);
                break;
            case "光照":
                dust.setIllumination(value);
                break;
            case "PM10":
                dust.setPm10(value);
                break;
            case "PM2.5":
                dust.setPm25(value);
                break;
            case "TSP":
                dust.setTsp(value);
                break;
            // 可扩展其他字段
        }
    }
    private static String mapDeviceStatus(String status) {
        // normal:正常,alarming:报警,preAlarming:预警,offline:离线
        return status;
    }

}
